package com.lwq.http.utils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.nio.client.CloseableHttpAsyncClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import com.lwq.http.threads.main.MainThread;

/**
* @author 作者 linweiqiang
* @version 创建时间：2017年10月19日 上午10:46:04
* 类说明
*/
public class SendHttpUtils {
	/**
	 * 发送Post请求
	 * @param uri 路径
	 * @param params 参数
	 * @return HttpPost
	 * @throws UnsupportedEncodingException
	 */
	public static HttpPost sendPost(String uri,Map<String,String> params) throws UnsupportedEncodingException{
		HttpPost hp = new HttpPost(uri);
		HttpEntity he = map2Entity(params);
		hp.setEntity(he);
		return hp;
	}
	
	public static HttpGet sendGet(String uri,Map<String ,String> params) throws ParseException, IOException{
		HttpEntity he = map2Entity(params);
		String param = EntityUtils.toString(he);
		HttpGet hg = new HttpGet(uri + "?" + param);
		return hg;
	}
	
	public static HttpEntity map2Entity(Map<String,String> map) throws UnsupportedEncodingException{
		List<NameValuePair> list =  new ArrayList<NameValuePair>();
		for (String key: map.keySet()) {
			list.add(new BasicNameValuePair(key, map.get(key)));
		}
		HttpEntity he = new UrlEncodedFormEntity(list);
		return he;
	}
	
	
	public static void closeableHttpAsyncClient(CloseableHttpAsyncClient ahac){
		if(ahac != null){
			try {
				ahac.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	public static void closeableHttpResponse(CloseableHttpResponse chr){
		if(chr != null){
			try {
				chr.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
